import http
import io
import os
from typing import List

from fastapi import APIRouter, Depends, UploadFile, HTTPException
import json
from sqlalchemy import select, desc, func, distinct
from sqlalchemy.ext.asyncio import AsyncSession
from apis.deps import get_db
from schemas import WeeklyReportCreate, WeeklyReportUpdate, WeeklyReportOut as WeeklyReport, Result, ResultPlus
from crud import weeklyReport
from utils import resp_200, IdNotExist
from models import WeeklyReport as WeeklyReportModel

router = APIRouter()


@router.post("/create_weeklyReport", response_model=Result, summary="新增项目")
async def create_weeklyReport(weeklyReport_in: WeeklyReportCreate, db: AsyncSession = Depends(get_db)):
    await weeklyReport.create(db=db, obj_in=weeklyReport_in)
    return resp_200(msg=f"添加了{weeklyReport_in.name}项目.")


@router.get("/", response_model=ResultPlus[WeeklyReport], summary='查询项目')
async def get_weeklyReport(pageIndex: int = 1, pageSize: int = 10, queryName: str = '',
                           db: AsyncSession = Depends(get_db)):
    sql1 = select(WeeklyReportModel).offset((pageIndex - 1) * pageSize).limit(pageSize).where(
        WeeklyReportModel.name.like(f'%{queryName}%')).order_by(
        desc(WeeklyReportModel.id))
    result = await db.execute(sql1)
    weeklyReportList = result.scalars().all()
    sql2 = select(func.count(distinct(WeeklyReportModel.id)))
    count = await db.scalar(sql2)
    # count = await weeklyReport.get_number(db)
    # _weeklyReport = await weeklyReport.get_multi(db, pageIndex, pageSize)
    # return {"code":200, "msg": "查询成功", "data": {"count": count, "list": weeklyReportList}}
    return resp_200(data={"count": count, "list": weeklyReportList}, msg=f"查询成功")


@router.get('/getWeeklyReport')
async def get_weeklyReport_ORM(db: AsyncSession = Depends(get_db)):
    data = WeeklyReportModel.name
    return {data}


@router.put('/update_weeklyReport/{id}', response_model=Result, summary='通过 id 更新项目信息')
async def update_weeklyReport(id: int, weeklyReport_in: WeeklyReportUpdate,
                              db: AsyncSession = Depends(get_db)):
    rowcount = await weeklyReport.update(db, id, obj_in=weeklyReport_in)
    if not rowcount:  # 每次更新, 当前数据的更新时间会变, 只要id存在, 就会一直返回1
        raise IdNotExist(f"更新失败")
    return resp_200(msg=f"更新成功.")


@router.delete('/delete_weeklyReport/{id}', response_model=Result, summary='通过 id 删除项目信息')
async def delete_weeklyReport(id: int, db: AsyncSession = Depends(get_db)):
    rowcount = await weeklyReport.remove(db, id)
    if not rowcount:
        raise IdNotExist(err_desc=f"系统中不存在 id 为 {id} 的项目.")
    return resp_200(msg=f'成功删除 id 为 {id} 的项目.')


@router.post('/uploadFile')
async def uploadFile(file: UploadFile):
    filePath = os.path.join('static/imgs/', file.filename)
    with open(filePath, 'wb') as f:
        for line in file.file:
            f.write(line)
    return {"file": file.filename}
